package com.atguigu.gmall.user.controller;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.common.constant.RedisConst;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.common.util.IpUtil;
import com.atguigu.gmall.model.user.UserAddress;
import com.atguigu.gmall.model.user.UserInfo;
import com.atguigu.gmall.user.service.UserAddressService;
import com.atguigu.gmall.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * @author 搭忆长安
 * @version 1.0
 * @date 2021年07月08日 18:00
 * @ClassName:UserController
 * @Description: TODO
 */
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private UserAddressService userAddressService;
    @PostMapping("/login")
    public Result login(String username, String password, HttpServletRequest request){


        //登录校验
        UserInfo userInfo = userService.login(username, password);
        //判断是否校验通过
        if(userInfo==null){
            return  Result.fail("用户名或密码错误");
        }
        //生成token
        String token = UUID.randomUUID().toString().replace("-","");
        //自定义存储对象
        Map<String, Object> map = new HashMap<>();
        map.put("userId",userInfo.getId());
        //ip地址192.168.1.128 129
        map.put("ip",IpUtil.getIpAddress(request));
        //存储在redis
       stringRedisTemplate.boundValueOps(token).set(JSONObject.toJSONString(map));
       //返回用户
        Map<String,String> result = new Hashtable<>();
        result.put("token",token);
        result.put("nickName",userInfo.getNickName());
        return  Result.ok(result);
    }

    /**
     * 获取用户地址
     * @param userId
     * @return
     */
    @GetMapping("/findUserAddressListByUserId/{userId}")
    public List<UserAddress> findUserAddressListByUserId(@PathVariable("userId")String userId){
        return  userAddressService.findUserAddressListByUserId(userId);
    }

    public Result<List<UserAddress>> getUserAddress(){
        Long userId = 1L;
        List<UserAddress> userAddressList = userService.getUserAddressList(userId);
        return Result.ok(userAddressList);
    }
}
